package com.das.mechanic_base.widget;

import android.content.Context;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.main.X3EditFaultLightAdapter;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.common.AwsFileBean;
import com.das.mechanic_base.bean.create.QuesSystemSnBean;
import com.das.mechanic_base.bean.main.DetectionNewBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.X3StringUtils;
import com.kproduce.roundcorners.RoundButton;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class X3EditFaultightDialog extends X3BaseBottomSheetDialog implements View.OnClickListener, X3MemberButtonView.IOnClickAffirm {

    private RecyclerView rlv_light;
    private X3EditFaultLightAdapter lightAdapter;
    private X3MemberButtonView rv_check;
    private RoundButton tv_edit;
    private boolean isCamera;
    private String path;
    private List<String> sList;
    private String questionToSystemSn;

    public X3EditFaultightDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        rlv_light = findViewById(R.id.recyclerview);
        rv_check = findViewById(R.id.rv_check);
        tv_edit = findViewById(R.id.tv_edit);
        tv_edit.setOnClickListener(this);
        rv_check.changeBtnStatus(true);
        rv_check.setiOnClickAffirm(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        rlv_light.setLayoutManager(linearLayoutManager);
        lightAdapter = new X3EditFaultLightAdapter(mContext);
        rlv_light.setAdapter(lightAdapter);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_dialog_editfaultlight;
    }

    public void setQuestionSystemSn(String questionToSystemSn,long receiveBaseId,boolean isCamera,String path,List<String> sList) {
        this.isCamera = isCamera;
        this.path = path;
        this.questionToSystemSn = questionToSystemSn;

        Log.e("SSSS","已经选中的:" + sList.toString());
        
        Map<String,Object> map = new HashMap<>();
        map.put("questionToItemSn", questionToSystemSn);
        map.put("receiveBaseId",receiveBaseId);
        NetWorkHttp.getApi().getNewQuestionSystemSn(map)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<QuesSystemSnBean>() {
                    @Override
                    protected void onDone(QuesSystemSnBean snBean) {
                        if (snBean == null) {
                            return;
                        }
                        List<String> optionsList = snBean.optionsList;
                        List<String> afterList = new ArrayList<>();
                        if (X3StringUtils.isListEmpty(optionsList)) {
                            return;
                        }
                        for (int i = 0; i < optionsList.size(); i++) {
                            String options = optionsList.get(i).replace(". ","_");
                            afterList.add(options);
                        }
                        if (lightAdapter != null) {
                            lightAdapter.setList(afterList,sList);
                        }

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_edit) {
            dismiss();
        }
    }

    @Override
    public void iOnClickAffirm() {
        if (lightAdapter == null) {
            rv_check.reset();
            return;
        }
        sList = lightAdapter.getsList();
        if (X3StringUtils.isListEmpty(sList)) {
            rv_check.reset();
            return;
        }
        if (X3StringUtils.isEmpty(path)) {
            saveEditLightSuccess("");
            return;
        }
        if (isCamera) {
            // 需要上传图片
            savePicture();
            return;
        }
        saveEditLightSuccess(path);
    }

    private void savePicture() {
        File imgFile = new File(path);

        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), imgFile);

        String filename = null;
        try {
            filename = URLEncoder.encode(imgFile.getName(), "UTF-8");

            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            Map<String, RequestBody> map = new HashMap<>();

            map.put("description",RequestBody.create(MediaType.parse("multipart/form-data"), "初检图片"));

            map.put("ossBucketName",RequestBody.create(MediaType.parse("multipart/form-data"), "SERVICE_PIC"));

            NetWorkHttp.getApi().uploadFileAws(map,fileBody,new HashMap<>())
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(((X3IBaseView)mContext).bindToLife())
                    .subscribe(new HttpCallBack<AwsFileBean>() {
                        @Override
                        protected void onDone(AwsFileBean awsFileBean) {
                            if (awsFileBean == null) {
                                return;
                            }
                            saveEditLightSuccess(awsFileBean.downloadUrl);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void NoNetCallBack() {
                            super.NoNetCallBack();
                            rv_check.reset();
                        }

                        @Override
                        protected void showError(String error) {
                            rv_check.reset();
                        }
                    });

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void saveEditLightSuccess(String downloadUrl) {
        rv_check.reset();
        DetectionNewBean.QuestionToItemDetectionBean detectionBean = new DetectionNewBean.QuestionToItemDetectionBean();
        List<String> tmp = new ArrayList<>();
        tmp.add(downloadUrl);
        detectionBean.itemUrlList = tmp;
        detectionBean.sn = questionToSystemSn;

        List<DetectionNewBean.QuestionToItemDetectionBean.QuestionListBean> questionListBeans = new ArrayList<>();
        for (int i = 0; i < sList.size(); i++) {
            String answer = sList.get(i).replace("\\. ", "_");
            DetectionNewBean.QuestionToItemDetectionBean.QuestionListBean listBean = new DetectionNewBean.QuestionToItemDetectionBean.QuestionListBean();
            listBean.answer = answer;
            listBean.iconRes = X3StringUtils.getLightSpan(answer);
            questionListBeans.add(listBean);
        }
        detectionBean.questionList = questionListBeans;

        if (iOnEditLight != null) {
            iOnEditLight.iOnEditLight(detectionBean,questionToSystemSn);
        }
        dismiss();
    }

    IOnEditLight iOnEditLight;

    public X3EditFaultightDialog setiOnEditLight(IOnEditLight iOnEditLight) {
        this.iOnEditLight = iOnEditLight;
        return this;
    }

    public interface IOnEditLight {

        void iOnEditLight(DetectionNewBean.QuestionToItemDetectionBean detectionBean,String questionSystemSn);
    }

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("初检信息故障灯编辑弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("初检信息故障灯编辑弹窗");
    }
}
